package com.freesky.provider.search.message;

import com.freesky.common.dao.mapper.ItemMapper;
import com.freesky.provider.search.mapper.ItemSearchMapper;
import com.freesky.provider.search.vo.SearchItem;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

/**
 * 监听商品修改消息，接收消息后，将对应的商品信息同步到索引库
 */
@Component
public class ItemMessageListener {

    private final static Logger logger = LoggerFactory.getLogger(ItemMessageListener.class);

    @Autowired
    private ItemSearchMapper itemSearchMapper;

    @Value("${solr.core}")
    private String coreName;

    @Autowired
    private HttpSolrClient client;

    private final String DESTINATION_NAME = "synchIndex";

    @JmsListener(destination = DESTINATION_NAME)
    public void receiveQueue(String msg) {
        logger.info("接收到消息：{}",msg);
        try {
            //从消息中取商品id
            String[] text = msg.split(",");
            String oprate = text[0];
            String itemId = text[1];
            if ("add".equals(oprate)) {
                //根据商品id查询商品信息
                SearchItem searchItem = itemSearchMapper.getItemById(itemId);
                if (searchItem!=null) {
                    String image = searchItem.getPicUrl();
                    if (image != null && !"".equals(image)) {
                        String[] strings = image.split(",");
                        image = strings[0];
                    } else {
                        image = "";
                    }
                    searchItem.setPicUrl(image);
                    // 创建Document对象
                    SolrInputDocument document = new SolrInputDocument();
                    document.addField("id", searchItem.getItemId());
                    document.addField("itemId", searchItem.getItemId());
                    document.addField("salePrice", searchItem.getSalePrice());
                    document.addField("itemName", searchItem.getItemName());
                    document.addField("subTitle", searchItem.getSubTitle());
                    document.addField("picUrl", searchItem.getPicUrl());
                    document.addField("categoryName", searchItem.getCategoryName());
                    document.addField("cid", searchItem.getCid());
                    client.add(coreName,document);
                    client.commit(coreName);
                }
            } else if ("delete".equals(text[0])) {
                client.deleteById(String.valueOf(itemId));
                client.commit(coreName);
            }
            logger.info("处理消息成功");
            client.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
